from ironcap.models import nodes
from ironcap.models import tags
from ironcap.models import votes
from ironcap.models import counters
from google.appengine.ext import db

class Page(nodes.ReferenceNode):
	url      = db.StringProperty  (indexed=True)
	mime     = db.StringProperty  ()
	code     = db.TextProperty    ()
	template = db.TextProperty    ()
	
	counter  = db.ReferenceProperty(counters.Counter)
	tags     = db.ReferenceProperty(tags.TagList)
	votes    = db.ReferenceProperty(votes.Votes)
	
	@classmethod
	def create(cls, **kwds):
		""" deletes this page and associated references """
		ret         = super(Page, cls).create(**kwds)
		ret.counter = counters.Counter.create(reference=ret)
		ret.tags    = tags.TagList.create(reference=ret)
		ret.votes   = votes.Votes.create(reference=ret)
		for k,v in kwds.iteritems():
			setattr(ret, k, v)
		ret.put()
		return ret
		
	@classmethod
	def get_by_url(cls, url):
		""" returns this page by the url """
		return db.Query( cls ).filter( 'url', url ).get()
	
	def delete(self):
		""" deletes this page and associated objects """
		try:
			if self.tags:
				self.tags.delete()
		except:
			pass
		try:
			if self.counter:
				self.counter.delete()
		except:
			pass
		try:
			if self.votes:
				self.votes.delete()
		except:
			pass
		nodes.ReferenceNode.delete(self)	